//
//  LGConsultHistoryController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2025/6/24.
//

#import "LGConsultHistoryController.h"
//患者详情
#import "LGPatientDetailController_YHJK.h"
#import "LGPatientDetailController2.h"
//医生详情
#import "LGPersionalDataController.h"
//订单详情
#import "LGOrderDetailController.h"
//服务部详情
#import "LGServiceDetailController.h"
//随访记录
#import "LGFollowAdviceRecordController.h"

#import "TUIBaseMessageController.h"
#import "TUIChatConversationModel.h"
#import "TUIMessageController.h"
#import "TUIMessageCellData.h"
#import "TUICommonModel.h"
#import "TUIChatConfig.h"


#import "LGBubbleMessageCell.h"
#import "LGTextMessageCell.h"
#import "LGSystemMessageCell.h"
#import "LGVoiceMessageCell.h"
#import "LGImageMessageCell.h"
#import "LGFaceMessageCell.h"
#import "LGVideoMessageCell.h"

//自定义消息
#import "LGPatientCardRecordCell.h"

#import "LGConsultStartEndCell2.h"
#import "LGCustomTextMessageCell2.h"
#import "LGConsultationAdviceCell2.h"
#import "LGRecommendDoctorCell2.h"
#import "LGRecommendServiceCell2.h"
#import "LGConsultEvaluationCell2.h"
#import "LGFollowUpRecommedCell2.h"
#import "LGCustomCellData.h"

//语音、视频、图片 - 播放、放大 工具
#import "LGMessageRecordManager.h"
#import "LGMessageMediaView.h" //图片查看大图
#import "TUIMediaCollectionCell.h"

#import "LGChatPatientNavigation.h"

#import "TUIMessageDataProvider.h"

@interface LGConsultHistoryController ()<UITableViewDelegate,UITableViewDataSource,LGMessageRecordDelegate>
/**   */
@property (nonatomic , strong)LGChatPatientNavigation *patientNavigation;
/**   */
@property (nonatomic , strong)TUIMessageDataProvider *messageDataProvider;

@property (nonatomic , strong)TUIBaseMessageController *messageController;
/**   */
@property (nonatomic , assign)LGMessageRecordManager *manager;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**  系统消息类型 */
@property (nonatomic , strong)NSArray *systemArray;
/**   */
@property (nonatomic , strong)NSArray *mediaArray;
/**   */
@property (nonatomic , strong)NSMutableDictionary *heightDic;

@end

@implementation LGConsultHistoryController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    self.manager = [LGMessageRecordManager sharedManager];
    [self.view addSubview:self.patientNavigation];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[LGTextMessageCell class] forCellReuseIdentifier:@"TIMTextElem"];
    [self.tableView registerClass:[LGVoiceMessageCell class] forCellReuseIdentifier:@"TIMSoundElem"];
    [self.tableView registerClass:[LGImageMessageCell class] forCellReuseIdentifier:@"TIMImageElem"];
    [self.tableView registerClass:[LGVideoMessageCell class] forCellReuseIdentifier:@"TIMVideoFileElem"];
    [self.tableView registerClass:[LGPatientCardRecordCell class] forCellReuseIdentifier:@"TIMCustom_02"];
    [self.tableView registerClass:[LGRecommendDoctorCell2 class] forCellReuseIdentifier:@"TIMCustom_08"];
    [self.tableView registerClass:[LGRecommendServiceCell2 class] forCellReuseIdentifier:@"TIMCustom_09"];
    [self.tableView registerClass:[LGConsultEvaluationCell2 class] forCellReuseIdentifier:@"TIMCustom_10"];
    [self.tableView registerClass:[LGFollowUpRecommedCell2 class] forCellReuseIdentifier:@"TIMCustom_17"];
    [self.tableView registerClass:[LGConsultationAdviceCell2 class] forCellReuseIdentifier:@"TIMCustom_20"];
    self.systemArray = @[@"TIMCustom_01",@"TIMCustom_03",@"TIMCustom_05",@"TIMCustom_07",@"TIMCustom_12",@"TIMCustom_13",@"TIMCustom_15",@"TIMCustom_16",@"TIMCustom_18",@"TIMCustom_30",@"TIMCustom_31"];
    
    //自定义添加消息
    NSArray *cellArray = @[
                          //自定义添加消息
                          @{BussinessID : @"TIMCustom_01",//发起咨询
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          },
                          @{BussinessID : @"TIMCustom_03",//咨询已开启
                            TMessageCell_Name : @"LGConsultStartEndCell2",
                          },
                          @{BussinessID : @"TIMCustom_05",//延长咨询时间
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          },
                          @{BussinessID : @"TIMCustom_07",//咨询已结束
                            TMessageCell_Name : @"LGConsultStartEndCell2",
                          },
                          @{BussinessID : @"TIMCustom_12",//视频咨询-发起就诊提示
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          },
                          @{BussinessID : @"TIMCustom_13",//问诊结束
                            TMessageCell_Name : @"LGConsultStartEndCell2",
                          },
                          @{BussinessID : @"TIMCustom_15",//视频通话
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          },
                          @{BussinessID : @"TIMCustom_16",//视频通话
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          },
                          @{BussinessID : @"TIMCustom_18",//咨询取消
                            TMessageCell_Name : @"LGConsultStartEndCell2",
                          },
                          @{BussinessID : @"TIMCustom_30",//候诊室
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          },
                          @{BussinessID : @"TIMCustom_31",//候诊室
                            TMessageCell_Name : @"LGCustomTextMessageCell2",
                          }];
   

    
    //自定义消息
    for (NSDictionary *messageInfo in cellArray) {
        NSString *bussinessID = messageInfo[BussinessID];
        NSString *cellName = messageInfo[TMessageCell_Name];
        Class cls = NSClassFromString(cellName);
        if (cls && bussinessID) {
            [self.tableView registerClass:cls forCellReuseIdentifier:bussinessID];
        }
    }
    self.patientNavigation.dataDic = self.dataDic;
    [self requestData];
    //查看医生详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDoctorDetail:) name:@"CheckDoctorDetail2" object:nil];
    //视频咨询订单详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkVideoOrderDetail:) name:@"CheckOrderDetail2" object:nil];
    //慢病服务详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkServiceDetail:) name:@"CheckServiceDetail2" object:nil];
    //去做评估
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkEvaluationDetail:) name:@"CheckEvaluationDetail2" object:nil];
    //查看医嘱详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDoctorAdviceDetail:) name:@"CheckDoctorAdviceDetail2" object:nil];
}

-(void)showEmptyView{
    [self.emptyView showViewWithImage:@"emptyView2" content:@"此功能待开发" offset:0];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/visit.Visit/appointmentChat" parameters:@{@"appointment_id":self.appointid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        NSMutableArray *dataArray = [NSMutableArray array];
        NSMutableArray *mediaArray = [NSMutableArray array];
        NSInteger currentTime = 0;
        NSArray *tempArray = returnData;
        for (NSInteger i=0; i<tempArray.count; i++) {
            NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:tempArray[i]];
            NSInteger time = [tempDic[@"message_time"] integerValue];
            if ((time - currentTime) > 5*60) {
                //大于5分钟 -- 显示时间
                [tempDic setValue:@"Y" forKey:@"showTime"];
            }else{
                [tempDic setValue:@"N" forKey:@"showTime"];
            }
            [dataArray addObject:tempDic];
            currentTime = time;
            
            NSString *type = LGNSString(tempDic[@"message_type"]);
            if ([type isEqualToString:@"image"]||[type isEqualToString:@"video"]) {
                [mediaArray addObject:tempDic];
            }
        }
        self.dataArray = [NSArray arrayWithArray:dataArray];
        self.mediaArray = [NSArray arrayWithArray:mediaArray];
        [self.tableView reloadData];
        
    } error:^(NSError *error) {
        
    }];
}



//查看患者详情
-(void)checkPatientDetailAction{
    if(_dataDic && _dataDic.allKeys.count>0){
        NSDictionary *tempDic = self.dataDic[@"patient"];
        NSString *nodePage = LGNSString(tempDic[@"nodepage"]);
        if ([nodePage isEqualToString:@"1"]) {
            //市一慢阻肺
            LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            //其他
            LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }
        
    }else{
        [TooltipView showMessage:@"此患者已被删除" offset:0];
    }
}

//查看推荐医生详情
-(void)checkDoctorDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGPersionalDataController *controller = [[LGPersionalDataController alloc]init];
    controller.userId = LGNSString(tempDic[@"doctorId"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//查看视频咨询订单详情
-(void)checkVideoOrderDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGOrderDetailController *controller = [[LGOrderDetailController alloc]init];
    controller.appointId = LGNSString(tempDic[@"appointId"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//服务包详情
-(void)checkServiceDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGServiceDetailController *controller = [[LGServiceDetailController alloc]init];
    controller.vipId = LGNSString(tempDic[@"vipId"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//去做量表评估
-(void)checkEvaluationDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
    controller.urlStr = LGNSString(tempDic[@"urlStr"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//随访及医嘱记录
-(void)checkDoctorAdviceDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGFollowAdviceRecordController *controller = [[LGFollowAdviceRecordController alloc]init];
    controller.patientid = self.dataDic[@"patient"][@"patient_id"];
    [self.navigationController pushViewController:controller animated:YES];
}


//播放语音
- (void)playVoiceMessage:(NSDictionary *)dataDic cell:(LGBubbleMessageCell *)cell{
    LGVoiceMessageCell *voiceCell = (LGVoiceMessageCell *)cell;
    [self.manager playVoiceMessage:dataDic cell:voiceCell];
}

//查看图片大图
- (void)showImageMessage:(NSDictionary *)dataDic cell:(LGBubbleMessageCell *)cell{
    LGImageMessageCell *imageCell = (LGImageMessageCell *)cell;
    CGRect frame = [imageCell.thumb convertRect:imageCell.thumb.bounds toView:[UIApplication sharedApplication].delegate.window];
    LGMessageMediaView *mediaView = [[LGMessageMediaView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
    mediaView.dataArray = self.mediaArray;
    [mediaView setThumb:imageCell.thumb frame:frame];
    [mediaView showMediaView:dataDic];
    [[UIApplication sharedApplication].keyWindow addSubview:mediaView];
}

//播放视频
- (void)showVideoMessage:(NSDictionary *)dataDic cell:(LGBubbleMessageCell *)cell{
    LGVideoMessageCell *videoCell = (LGVideoMessageCell *)cell;
    CGRect frame = [videoCell.thumbView convertRect:videoCell.thumbView.bounds toView:[UIApplication sharedApplication].delegate.window];
    LGMessageMediaView *mediaView = [[LGMessageMediaView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
    mediaView.dataArray = self.mediaArray;
    [mediaView setThumb:videoCell.thumbView frame:frame];
    [mediaView showMediaView:dataDic];
    [[UIApplication sharedApplication].keyWindow addSubview:mediaView];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    static CGFloat screenWidth = 0;
    if (screenWidth == 0) {
        screenWidth = Screen_Width;
    }
    return [self getCellDataHeightAtIndex:indexPath.row Width:screenWidth];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.row];
    NSString *reuseId = LGNSString(tempDic[@"original_msg_type"]);
    if ([LGNSString(tempDic[@"original_msg_type"]) isEqualToString:@"TIMCustomElem"]) {
        //自定义消息
        NSDictionary *dataDic = [ObjectTool jsonToObject:tempDic[@"content"][@"data"]];
        reuseId = LGNSString(dataDic[@"businessID"]);
        if ([self.systemArray containsObject:reuseId]) {
            LGSystemMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.dataDic = tempDic;
            return cell;
        }else{
            LGBubbleMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.dataDic = tempDic;
            cell.delegate = self;
            return cell;
        }
    }else{
        LGBubbleMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataDic = tempDic;
        cell.delegate = self;
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    NSLog(@">>>???>>>%@",dataDic);
}


- (CGFloat)getCellDataHeightAtIndex:(NSUInteger)index Width:(CGFloat)width {
    CGFloat height = 0;
    CGFloat timeHeight = 0;
    @autoreleasepool {
        if (index < self.dataArray.count) {
            NSDictionary *tempDic = self.dataArray[index];
            //是否显示时间
            timeHeight = [LGNSString(tempDic[@"showTime"]) isEqualToString:@"Y"]?20:0;
            //消息类型
            NSString *key = LGNSString(tempDic[@"message_id"]);
            if ([self.heightDic.allKeys containsObject:key]) {
                height = [[self.heightDic objectForKey:key] floatValue];
            }
            if (height == 0) {
                NSString *msgType = LGNSString(tempDic[@"original_msg_type"]);
                if ([msgType isEqualToString:@"TIMCustomElem"]) {
                    //自定义消息
                    NSDictionary *dataDic = [ObjectTool jsonToObject:tempDic[@"content"][@"ext"]];
                    NSDictionary *customDic = [ObjectTool jsonToObject:tempDic[@"content"][@"data"]];
                    NSString *reuseId = LGNSString(customDic[@"businessID"]);
                    height = [LGCustomCellData caculateCellHeight:dataDic];
                    if (![self.systemArray containsObject:reuseId]) {
                        height += viewPix(40);
                    }

                }else if ([msgType isEqualToString:@"TIMTextElem"]){
                    height = [self heightWithType:@"TIMTextElem" dataDic:tempDic];
                    
                }else if ([msgType isEqualToString:@"TIMSoundElem"]){
                    height = [self heightWithType:@"TIMSoundElem" dataDic:tempDic];
                    
                }else if ([msgType isEqualToString:@"TIMImageElem"]){
                    height = [self heightWithType:@"TIMImageElem" dataDic:tempDic];
                    
                }else if ([msgType isEqualToString:@"TIMVideoFileElem"]){
                    height = [self heightWithType:@"TIMVideoFileElem" dataDic:tempDic];
                }
                [self.heightDic setObject:@(height) forKey:key];
            }
        }
    }
    return height+timeHeight;
}


-(CGFloat)heightWithType:(NSString *)msgType dataDic:(NSDictionary *)dataDic{
    NSString *sender = LGNSString(dataDic[@"sender"]);
    TMsgDirection direction = [sender isEqualToString:@"member"]?MsgDirectionIncoming:MsgDirectionOutgoing;
    CGFloat height = 0;
    if ([msgType isEqualToString:@"TIMTextElem"]){
        //文字
        TUITextMessageCellData *textData = [[TUITextMessageCellData alloc]initWithDirection:direction];
        textData.content = LGNSString(dataDic[@"content"][@"text"]);
        height = 60 + [textData contentSize].height;
        
    }else if ([msgType isEqualToString:@"TIMSoundElem"]){
        //语音
        TUIVoiceMessageCellData *voiceData = [[TUIVoiceMessageCellData alloc]initWithDirection:direction];
        voiceData.duration = [dataDic[@"content"][@"second"] intValue];
        voiceData.length = [dataDic[@"content"][@"size"] intValue];
        height = 60 + [voiceData contentSize].height;
        
    }else if ([msgType isEqualToString:@"TIMImageElem"]){
        //图片
        NSDictionary *thumDic = [dataDic[@"content"] lastObject];
        CGFloat thumHeight = [thumDic[@"height"] floatValue];
        CGFloat thumWidth = [thumDic[@"width"] floatValue];
        if(thumHeight > thumWidth){
            thumWidth = thumWidth / thumHeight * TImageMessageCell_Image_Height_Max;
            thumHeight = TImageMessageCell_Image_Height_Max;
        } else {
            thumHeight = thumHeight / thumWidth * TImageMessageCell_Image_Width_Max;
            thumWidth = TImageMessageCell_Image_Width_Max;
        }
        height = 60 + thumHeight;
        
    }else if ([msgType isEqualToString:@"TIMVideoFileElem"]){
        //视频
        CGFloat thumHeight = [dataDic[@"content"][@"thumb_height"] floatValue];
        CGFloat thumWidth = [dataDic[@"content"][@"thumb_width"] floatValue];
        if(thumHeight > thumWidth){
            thumWidth = thumWidth / thumHeight * TVideoMessageCell_Image_Height_Max;
            thumHeight = TVideoMessageCell_Image_Height_Max;
        } else {
            thumHeight = thumHeight / thumWidth * TVideoMessageCell_Image_Width_Max;
            thumWidth = TVideoMessageCell_Image_Width_Max;
        }
        height = 60 + thumHeight;
    }
    if (height < 55) height = 55;
    return height;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = TUIChatDynamicColor(@"chat_controller_bg_color", @"#EDEDED");
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 60;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(LGChatPatientNavigation *)patientNavigation{
    if(!_patientNavigation){
        _patientNavigation = [[LGChatPatientNavigation alloc]initWithFrame:CGRectMake(0, 0, Screen_W, topBarHeight)];
        _patientNavigation.showStatusView = NO;
        [_patientNavigation.backBtn addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_patientNavigation.patientBtn addTarget:self action:@selector(checkPatientDetailAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _patientNavigation;
}

@end
